package com.hcloud.common.crud.advice;

import com.hcloud.common.core.base.HCloudResult;
import com.hcloud.common.core.exception.ServiceException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.List;

/**
 * @Auther hepangui
 * @Date 2018/11/2
 */
@RestControllerAdvice
public class ExceptionControllerAdvice {

    /**
     * 主要应对传入参数犹如导致的@Valid报错
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(BindException.class)
    public HCloudResult bindExceptionHandler(BindException ex) {
        List<FieldError> fieldErrors = ex.getFieldErrors();
        StringBuilder sb = new StringBuilder("");
        fieldErrors.forEach(msg -> sb.append(msg.getDefaultMessage()).append("\n"));
//        ex.printStackTrace();
        return new HCloudResult(sb.toString());
    }

    /**
     * 业务异常统一捕捉，controller层不用再写trycatch 节省代码
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public HCloudResult serviceExceptionHandler(ServiceException ex) {
        return new HCloudResult(ex.getMessage());
    }

    /**
     * 其它系统异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    public HCloudResult AccessDeniedExceptionHandler(Exception ex) {
        ex.printStackTrace();
        HCloudResult hCloudResult = new HCloudResult("权限不足");
        hCloudResult.setCode(HCloudResult.NOAUTH);
        return hCloudResult;
    }

    /**
     * 参数异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public HCloudResult IllegalArgumentExceptionHandler(Exception ex) {
        ex.printStackTrace();
        HCloudResult hCloudResult = new HCloudResult(ex.getMessage());
        hCloudResult.setCode(HCloudResult.FAIL);
        return hCloudResult;
    }

    /**
     * 其它系统异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public HCloudResult serviceExceptionHandler(Exception ex) {
        ex.printStackTrace();
        return new HCloudResult("发生未知错误");
    }

    /**
     * url错误
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public HCloudResult serviceExceptionHandler(NoHandlerFoundException ex) {
        return new HCloudResult("URL错误");
    }
}
